package calendar;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

/* main server class which starts the server and registers with rmiregistry */
public class CalendarServer
{
  public static void main(String argv[]) throws InterruptedException
  {
    FileInputStream file;
    CalendarMgr manager = null;
    
    System.out.println("Server: Registering CalendarService" + argv[2] );
      
    manager = new CalendarMgr();
      
    String host      = argv[0];
    int port         = Integer.parseInt(argv[1]);
    String type      = argv[2];
    String replicaHost = argv[3];
    int replicaPort  = Integer.parseInt(argv[4]);

    try {
      /* attempt to read in the persistent calendar data */
      file = new FileInputStream ( "CalendarMgr" + argv[2] + ".data" );
      if ( file != null )
      {
        ObjectInputStream in;
        try
        {
          in = new ObjectInputStream(file);
          System.out.println( "Server: Loading persistent data from disk." );
          manager = (CalendarMgr)in.readObject();
        }
        catch(Exception ex)
        {
          System.out.println( "CalendarServer: main -> " + ex );
        }
      }
      
    }
    catch(FileNotFoundException ex)
    {
      System.out.println( "Server: Persistent data does not exist yet." );
    }

    manager.setParams( host, port, type, replicaHost, replicaPort );
    manager.reset();

    CalendarMgrSkeleton stub = new CalendarMgrSkeleton( manager, port, 
      port, "CalendarManager" + type );
    
    System.out.println("Server: Ready...");

    /* loops indefinitely, alerting clients of important events */
    while ( true )
    {
      try
      {
        Calendar cal = Calendar.getInstance();
        //cal.add( Calendar.MINUTE, -4 ); /* time adjustment for testing */
        Date now        = cal.getTime();
        ArrayList users = manager.list();
        Iterator itr    = users.iterator();
        while(itr.hasNext())
        {
          User u               = (User)itr.next();
          CalendarObj calendar = manager.getCalendar(u.getId());
          ArrayList events     = calendar.getEvents();
          Iterator itrEvents   = events.iterator();
          while ( itrEvents.hasNext() )
          {
            Event e = (Event)itrEvents.next();
            long diff = e.getStart().getTime() - now.getTime();
            if( Math.abs(diff) <= 1000 )
            {
              if ( !e.getIsSent() ) calendar.notifyClientEvent(e);
            }
          }
        }
      }
      catch(IOException ex)
      {
        System.out.println( "CalendarServer: main loop -> " + ex );
      }
      Thread.sleep( 900 );
      manager.connectReplica();
    }
  }
}
